package com.young.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * json工具类
 * @author wangjiyu@imdada.cn
 * @create 2018/12/25
 */
public class JsonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    static {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//设置遇到未知的参数不报错(json和bean的参数个数或者名称对不上时不报错)
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));//时间格式
    }

    /**
     * 对象转json
     * @param object 待转为json字符串的对象(支持list集合)
     * @return
     */
    public static String toJson(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("[JSON工具类-对象转json] 对象转json发生异常:", e);
        }
        return null;
    }

    /**
     * json字符串转bean(可以是list)
     * 适用于转简单的bean对象(内部不存在list等属性)
     * @param json json字符串
     * @param clazz 目标类class对象
     * @param <T>
     * @return
     */
    public static <T> T toBean(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("[JSON工具类-json转对象] json转对象发生异常,json={},clazz={},异常:", json, clazz, e);
        }
        return null;
    }

    /**
     * json字符串转bean(适用于复杂对象)
     * @param json json字符串
     * @param typeReference 目标类TypeReference对象
     * @param <T>
     * @return
     */
    public static <T> T toBean(String json, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(json, typeReference);
        } catch (IOException e) {
            logger.error("[JSON工具类-json转对象] json转对象发生异常,json={},异常:", json, e);
        }
        return null;
    }

}